<!DOCTYPE html>
<html lang="zh-CN">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>咨询记录查看</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link
      rel="stylesheet"
      href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css"
    />
    <style>
      .record-card {
        transition: transform 0.2s, box-shadow 0.2s;
      }
      .record-card:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
      }
      .skeleton {
        animation: pulse 1.5s infinite ease-in-out;
      }
      @keyframes pulse {
        0%,
        100% {
          opacity: 1;
        }
        50% {
          opacity: 0.5;
        }
      }
    </style>
  </head>
  <body class="bg-gray-50 min-h-screen py-10">
    <div class="max-w-4xl mx-auto px-4">
      <header class="text-center mb-10">
        <h1 class="text-3xl font-bold text-gray-800 mb-2">📝 咨询记录列表</h1>
      </header>
      <!-- 在 <header> 后添加 -->
      <div class="text-center mb-6">
        <button
          id="clear-btn"
          class="bg-red-500 hover:bg-red-600 text-white font-medium py-2 px-4 rounded-lg transition shadow"
        >
          <i class="fas fa-trash-alt mr-2"></i>清空所有记录
        </button>
      </div>
      <!-- 加载状态 -->
      <div id="loading" class="text-center py-8 hidden">
        <i class="fas fa-spinner fa-spin text-3xl text-primary mb-4"></i>
        <p class="text-gray-600">正在加载记录...</p>
      </div>

      <!-- 无数据提示 -->
      <div id="no-data" class="text-center py-10 hidden">
        <i class="fas fa-inbox text-5xl text-gray-300 mb-4"></i>
        <p class="text-gray-500 text-lg">暂无任何咨询记录</p>
      </div>

      <!-- 记录列表容器 -->
      <div id="records-container" class="space-y-6"></div>
    </div>

    <script>
      const recordsContainer = document.getElementById("records-container");
      const loadingEl = document.getElementById("loading");
      const noDataEl = document.getElementById("no-data");

      // 格式化时间（可选：更友好的显示）
      function formatTime(isoString) {
        const date = new Date(isoString);
        return date.toLocaleString("zh-CN", {
          year: "numeric",
          month: "2-digit",
          day: "2-digit",
          hour: "2-digit",
          minute: "2-digit",
          second: "2-digit",
        });
      }

      // 渲染单条记录
      function renderRecord(record) {
        const card = document.createElement("div");
        card.className =
          "record-card bg-white p-6 rounded-xl shadow-sm border border-gray-200";

        // 需求类型中文映射
        const typeMap = {
          "digital-twin": "工业数字孪生解决方案",
          modeling: "工业模型制作",
          consulting: "技术咨询服务",
          other: "其他需求",
          "": "未选择",
        };

        card.innerHTML = `
        <div class="flex justify-between items-start">
          <div>
            <h2 class="text-xl font-semibold text-gray-800">${
              record.name || "匿名"
            }</h2>
            <p class="text-gray-600 text-sm mt-1">${
              record.company || "未填写企业"
            }</p>
          </div>
          <span class="text-xs bg-blue-100 text-blue-800 px-2 py-1 rounded">${
            typeMap[record.inquiryType] || "未知类型"
          }</span>
        </div>

        <div class="mt-4 grid grid-cols-1 md:grid-cols-2 gap-3 text-sm">
          <div><i class="fas fa-envelope text-gray-400 mr-2"></i> ${
            record.email || "无邮箱"
          }</div>
          <div><i class="fas fa-phone text-gray-400 mr-2"></i> ${
            record.phone || "无电话"
          }</div>
        </div>

        ${
          record.message
            ? `
        <div class="mt-4">
          <p class="text-gray-700"><span class="font-medium">备注：</span>${record.message}</p>
        </div>`
            : ""
        }

        <div class="mt-4 pt-4 border-t border-gray-100 text-xs text-gray-500">
          <i class="fas fa-clock mr-1"></i> 提交于 ${formatTime(
            record.timestamp
          )}
        </div>
      `;
        return card;
      }

      // 获取并展示记录
      async function fetchAndDisplayRecords() {
        const password = prompt("🔒 请输入管理员密码查看咨询记录：");
        if (!password) {
          document.body.innerHTML =
            '<div class="min-h-screen flex items-center justify-center text-gray-500">未授权访问</div>';
          return;
        }

        loadingEl.classList.remove("hidden");
        recordsContainer.innerHTML = "";
        noDataEl.classList.add("hidden");

        try {
          const res = await fetch("/submissions", {
            headers: {
              Authorization: `Bearer ${password}`, // ← 关键：带上密码
            },
          });

          const result = await res.json();

          if (!res.ok) {
            // 后端返回 401 或其他错误
            throw new Error(result.message || "密码错误或服务器异常");
          }

          // 成功返回记录数组
          if (result.length === 0) {
            noDataEl.classList.remove("hidden");
          } else {
            result.forEach((record) => {
              recordsContainer.appendChild(renderRecord(record));
            });
          }
        } catch (err) {
          console.error("加载失败:", err);
          alert("❌ " + err.message);
          // 可选：允许重试
          setTimeout(fetchAndDisplayRecords, 500);
        } finally {
          loadingEl.classList.add("hidden");
        }
      }

      // ===== 删除数据 =====
      async function clearAllRecords() {
        const password = prompt("请输入管理员密码以清空所有记录：");
        if (password === null || password.trim() === "") {
          return; // 用户取消或未输入
        }

        try {
          const res = await fetch("/submissions", {
            method: "DELETE",
            headers: {
              "Content-Type": "application/json",
            },
            body: JSON.stringify({ password: password.trim() }),
          });

          const result = await res.json();

          if (!res.ok) {
            throw new Error(result.message || "密码错误或清空失败");
          }

          alert("✅ 所有记录已清空！");
          fetchAndDisplayRecords(); // 刷新列表
        } catch (err) {
          console.error("清空失败:", err);
          alert("❌ " + err.message);
        }
      }

      // 页面加载完成后绑定事件
      document.addEventListener("DOMContentLoaded", () => {
        fetchAndDisplayRecords();
        document
          .getElementById("clear-btn")
          .addEventListener("click", clearAllRecords);
      });
    </script>
  </body>
</html>
